package com.example.ioth5demo

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.webkit.*
import android.os.Build
import android.net.http.SslError
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.OnBackPressedCallback
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.platform.LocalContext
import com.example.ioth5demo.ui.theme.IotH5DemoTheme

@OptIn(ExperimentalMaterial3Api::class)
class MainActivity : ComponentActivity() {
    private var webView: WebView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        val backPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (webView?.canGoBack() == true) {
                    webView?.goBack()
                } else {
                    isEnabled = false
                    onBackPressedDispatcher.onBackPressed()
                }
            }
        }
        onBackPressedDispatcher.addCallback(this, backPressedCallback)

        setContent {
            IotH5DemoTheme {
                val url = "https://api.ximalaya.com/gatekeeper/iot-cloud-content#/"
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    WebViewContent(
                        url = url,
                        modifier = Modifier.padding(innerPadding),
                        linkedWebView = { webView = it }
                    )
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WebViewContent(url: String, modifier: Modifier = Modifier, linkedWebView: (WebView) -> Unit) {
    val context = LocalContext.current
    var canGoBack by remember { mutableStateOf(false) }
    var currentWebView: WebView? = null
    var pageTitle by remember { mutableStateOf("Loading...") }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(pageTitle) },
                navigationIcon = {
                    // 在次级页面才展示后退按钮
                    if (canGoBack) {
                        IconButton(onClick = { currentWebView?.goBack() }) {
                            Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                        }
                    }
                }
            )
        }
    ) { innerPadding ->
        AndroidView(
            modifier = modifier
                .fillMaxSize()
                .padding(innerPadding),
            factory = { ctx ->
                WebView(ctx).apply {
                    currentWebView = this
                    linkedWebView(this)
                    webViewClient = object : WebViewClient() {
                        @Deprecated("Deprecated in Java")
                        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                            return handleUrl(view, url)
                        }

                        private fun handleUrl(view: WebView?, url: String?): Boolean {
                            url?.let {
                                if (it.startsWith("http://") || it.startsWith("https://")) {
                                    if (it.startsWith("https://wx.tenpay.com")) {
                                        view?.loadUrl(it, mapOf("Referer" to "https://m.ximalaya.com"))
                                        return true
                                    }
                                    return false
                                }
                                try {
                                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(it))
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                    context.startActivity(intent)
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                    // 可以在这里添加错误处理，比如显示一个提示信息
                                }
                                return true
                            }
                            return false
                        }

                        override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
                            handler?.proceed()
                        }

                        override fun onPageFinished(view: WebView?, url: String?) {
                            super.onPageFinished(view, url)
                            view?.let {
                                canGoBack = it.canGoBack()
                            }
                        }
                    }

                    webChromeClient = object : WebChromeClient() {
                        override fun onReceivedTitle(view: WebView?, title: String?) {
                            super.onReceivedTitle(view, title)
                            pageTitle = title ?: "Web Page"
                        }
                    }

                    settings.apply {
                        javaScriptEnabled = true
                        domStorageEnabled = true
                        databaseEnabled = true
                        useWideViewPort = true
                        loadWithOverviewMode = true
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
                        }
                    }

                    loadUrl(url)
                }
            }
        )
    }
}
